from django.shortcuts import render, redirect
from django.views import generic
from django.http import HttpResponse
from django.apps import apps
from django.contrib.auth import logout

from users import forms as users_forms
from account import forms as account_forms
from account import utils


class HomePageDisplay(generic.View):

    """ Отображение домашней страницы пользователя """

    def get(self, request):

        return render(request, 'account/home_page.html')


class UserRegistration(generic.View):

    """ Регистрация пользователя """

    def get(self, request):

        form = users_forms.UserCreationForm()
        context = {'form': form}
        return render(request, 'registration/registration.html', context)

    def post(self, request):

        bound_form = users_forms.UserCreationForm(request.POST)

        if bound_form.is_valid():
            utils.register_user(request, bound_form)
            return redirect('account:entering_code')
        else:
            return render(request, 'registration/registration.html', {'form': bound_form})


class EnteringCode(generic.View):

    """ Ввод кода отправленного для подтверждения """

    def get(self, request):

        form = account_forms.EnteringCodeForm()
        return render(request, 'account/entering_code.html', {'form': form})

    def post(self, request):

        bound_form = account_forms.EnteringCodeForm(request.POST)

        if bound_form.is_valid():
            result = utils.check_code(request, bound_form)
            return result


class ShowingContent(generic.View):

    """ Отображаем какой-то контент """

    def get(self, request, content_type):

        model = apps.get_model(app_label='content', model_name=content_type)
        list_of_items = model.objects.all()
        context = {'content': list_of_items}


class UserLogin(generic.View):

    """ Авторизация пользователя """

    def get(self, request):

        form = account_forms.UserLoginForm()
        context = {'form': form}
        return render(request, 'registration/login.html', context)

    def post(self, request):

        bound_form = account_forms.UserLoginForm(request.POST)

        if bound_form.is_valid():
            result = utils.login_user(request, bound_form)
            return result
        else:
            return render(request, 'registration/login.html', {'form': bound_form})


class UserLogout(generic.View):

    """ Выходи из учетной записи пользователя """

    def get(self, request):

        logout(request)
        return redirect('account:user_login')
